package com.qdaily.ui.ui.fragment;

import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.LinearLayout;

import com.qdaily.supportlibrary.request.JsonData;
import com.qdaily.supportlibrary.util.LocalDisplay;
import com.qdaily.supportlibrary.util.NetUtil;
import com.qdaily.supportlibrary.util.QDJsonUtil;
import com.qdaily.supportlibrary.util.QLog;
import com.qdaily.supportlibrary.views.banner.SliderBanner;
import com.qdaily.ui.MainActivity;
import com.qdaily.ui.QDBaseFragment;
import com.qdaily.ui.R;
import com.qdaily.ui.net.NetConfigs;
import com.qdaily.ui.net.QDEnum;
import com.qdaily.ui.net.entity.ArticleListEntity;
import com.qdaily.ui.ui.adapter.ArticleListAdapter;
import com.qdaily.ui.ui.views.OnRefreshAndLoadMoreListener;
import com.qdaily.ui.ui.views.QDRefreshListView;
import com.qdaily.ui.ui.views.SliderBannerController;
import com.qdaily.ui.ui.views.TitleBar;

/**
 * Created by song on 15/5/11.
 */
public class CategoryFragment extends QDBaseFragment implements OnRefreshAndLoadMoreListener {

    private String TAG = "CategoryFragment";

    private SliderBanner sliderBanner;  //home使用
    private SliderBannerController sliderBannerController; //home使用

    private QDRefreshListView qdRefreshListView;
    private TitleBar viewTitleHeaderBar;
    private ArticleListAdapter adapter;
    private long lastDataTime = 0; //用于取数据
    private boolean isHasMore;
    private boolean isLoading;
    private boolean isLastListEmpty;

    /**
     * frg传值。
     */
    public static class CategoryDataObj {
        private QDEnum.CategoryFragmentEnum mCurCategoryFragmetType;
        private int categoryId;
        private String titleText = "";
        private boolean isTitlebarLeftBtnVisiable = false;

        public CategoryDataObj setIsTitlebarLeftBtnVisiable(boolean isTitlebarLeftBtnVisiable) {
            this.isTitlebarLeftBtnVisiable = isTitlebarLeftBtnVisiable;
            return this;
        }

        public CategoryDataObj setTitleText(String titleText) {
            this.titleText = titleText;
            return this;
        }

        public CategoryDataObj setCategoryFragmetType(QDEnum.CategoryFragmentEnum mCurCategoryFragmetType) {
            this.mCurCategoryFragmetType = mCurCategoryFragmetType;
            return this;
        }

        public CategoryDataObj setCategoryId(int categoryId) {
            this.categoryId = categoryId;
            return this;
        }

        public QDEnum.CategoryFragmentEnum getmCurCategoryFragmetType() {
            return mCurCategoryFragmetType;
        }

        public int getCategoryId() {
            return categoryId;
        }

        public String getTitleText() {
            return titleText;
        }

        public boolean isTitlebarLeftBtnVisiable() {
            return isTitlebarLeftBtnVisiable;
        }

        @Override
        public boolean equals(Object o) {
            if (o instanceof CategoryDataObj) {
                CategoryDataObj obj = (CategoryDataObj) o;
                if (obj.getmCurCategoryFragmetType() == this.getmCurCategoryFragmetType() && obj.getCategoryId() == this.getCategoryId() && obj.getTitleText().equals(this.getTitleText()) && obj.isTitlebarLeftBtnVisiable() == this.isTitlebarLeftBtnVisiable()) {
                    return true;
                }
            }
            return super.equals(o);
        }

        @Override
        public String toString() {
            return this.getmCurCategoryFragmetType() + "," + this.getCategoryId() + "," + this.getTitleText() + "," + this.isTitlebarLeftBtnVisiable();
        }
    }

    private CategoryDataObj categoryDataObj;

    @Override
    public void onEnter(Object data) {
        if (null != mDataIn && !mDataIn.equals(data)) {
            categoryDataObj = (CategoryDataObj) data;
            adapter.clearData();
            adapter.notifyDataSetChanged();
            titlebarLogic(categoryDataObj);
//            qdRefreshListView.autoRefresh();
            onRefreshBegin();
        }
        super.onEnter(data);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.view_pullrefresh_titlebar;
    }

    @Override
    protected void setupViews(View view) {
        categoryDataObj = (CategoryDataObj) mDataIn;
        if (null == categoryDataObj) {
            categoryDataObj = new CategoryDataObj().
                    setCategoryFragmetType(QDEnum.CategoryFragmentEnum.HOME)
                    .setCategoryId(0);
        }
        qdRefreshListView = (QDRefreshListView) view.findViewById(R.id.category_refreshListView);
        viewTitleHeaderBar = (TitleBar) view.findViewById(R.id.viewTitleHeaderBar);
        adapter = new ArticleListAdapter(getContext());

        titlebarLogic(categoryDataObj);

        if (categoryDataObj.mCurCategoryFragmetType == QDEnum.CategoryFragmentEnum.HOME) {
            View bannerHeaderView = LayoutInflater.from(getContext()).inflate(R.layout.view_banner, null);
            sliderBanner = (SliderBanner) bannerHeaderView.findViewById(R.id.sliderBanner);
            sliderBannerController = new SliderBannerController(getContext(), sliderBanner);
            qdRefreshListView.addHeaderView(bannerHeaderView);
        }

        if (categoryDataObj.mCurCategoryFragmetType == QDEnum.CategoryFragmentEnum.BESTDESIGN) {
            adapter.setIsBestDesign(true);
        }

        qdRefreshListView.setOnRefreshAndLoadMoreListener(this);
        if (getActivity() instanceof MainActivity) {
            final MainActivity activity = (MainActivity) getActivity();
            qdRefreshListView.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                    activity.onChildScrollStateChange(view, scrollState);
                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                }
            });
            qdRefreshListView.setOnTouchListener(new View.OnTouchListener() {
                private float y;
                private int scrollFlagY = 10;

                @Override
                public boolean onTouch(View var1, MotionEvent event) {
                    int my = 0;
                    switch (event.getAction() & MotionEvent.ACTION_MASK) {
                        case MotionEvent.ACTION_DOWN:
                            y = event.getY();
                            break;
                        case MotionEvent.ACTION_MOVE:
                            if (y == 0) {
                                y = event.getY();
                            }
                            my = (int) (event.getY() - y);
                            if (my < -scrollFlagY) {
                                activity.onChildScroll(false);
                            } else if (my > scrollFlagY) {
                                activity.onChildScroll(true);
                            }
                            break;
                        default:
                            y = 0;
                            break;
                    }
                    return false;
                }
            });
        }
    }

    private void titlebarLogic(CategoryDataObj categoryDataObj) {
        if (categoryDataObj.mCurCategoryFragmetType == QDEnum.CategoryFragmentEnum.HOME || categoryDataObj.mCurCategoryFragmetType == QDEnum.CategoryFragmentEnum.PAPER) {
            viewTitleHeaderBar.setVisibility(View.GONE);
        } else {
            viewTitleHeaderBar.setVisibility(View.VISIBLE);
        }

        if (categoryDataObj.isTitlebarLeftBtnVisiable) {
            this.viewTitleHeaderBar.getImageViewTitleBarLeft().setVisibility(View.VISIBLE);
        } else {
            this.viewTitleHeaderBar.getImageViewTitleBarLeft().setVisibility(View.GONE);
        }

        this.viewTitleHeaderBar.setTitle(categoryDataObj.titleText);
        this.viewTitleHeaderBar.onBack();
    }

    @Override
    protected void setupData() {
        if (categoryDataObj.mCurCategoryFragmetType == QDEnum.CategoryFragmentEnum.HOME) {
            LinearLayout.LayoutParams lyp = new LinearLayout.LayoutParams(LocalDisplay.SCREEN_WIDTH_PIXELS, SliderBannerController.Height);
            sliderBanner.setLayoutParams(lyp);
            sliderBanner.setPadding(0, 0, 0, LocalDisplay.designedDP2px(2));
        }
        qdRefreshListView.setAdapter(adapter);
        onRefreshBegin();
    }

    @Override
    protected void onRequestCallBack(NetUtil.NetParams params, JsonData response) {
        QLog.time(QDTAG + "onRequestCallBack");
        super.onRequestCallBack(params, response);
        isLoading = false;
        boolean isFirst = false;
        ArticleListEntity articleListEntity = null;
        if (params instanceof NetConfigs.RequestCategoriesArticles) {
            NetConfigs.RequestCategoriesArticles requestCategoriesArticles = (NetConfigs.RequestCategoriesArticles) params;
            isFirst = requestCategoriesArticles.getmLastTime() == 0;
        } else if (params instanceof NetConfigs.RequestHomesDada) {
            NetConfigs.RequestHomesDada requestHomesDada = (NetConfigs.RequestHomesDada) params;
            isFirst = requestHomesDada.getmLastTime() == 0;
        } else if (params instanceof NetConfigs.RequestTagsArticles) {
            NetConfigs.RequestTagsArticles requestTagsArticles = (NetConfigs.RequestTagsArticles) params;
            isFirst = requestTagsArticles.getmLastTime() == 0;
        } else if (params instanceof NetConfigs.RequestMyFavorite) {
            NetConfigs.RequestMyFavorite requestMyFavorite = (NetConfigs.RequestMyFavorite) params;
            isFirst = requestMyFavorite.getmLastTime() == 0;
        } else if (params instanceof NetConfigs.RequestRadarList) {
            NetConfigs.RequestRadarList requestRadarList = (NetConfigs.RequestRadarList) params;
            isFirst = requestRadarList.getmLastTime() == 0;
        }
        articleListEntity = QDJsonUtil.Json2Object(response.toString(), ArticleListEntity.class);
        if (null != articleListEntity && articleListEntity.getMeta().getStatus() == NetConfigs.HTTP_RESPONSE_200) {
            if (isFirst) //说明请求的第一页
            {
                isLastListEmpty = adapter.addTopData(articleListEntity.getResponse().getFeeds().getList());
                if (categoryDataObj.mCurCategoryFragmetType == QDEnum.CategoryFragmentEnum.HOME)
                    sliderBannerController.play(articleListEntity.getResponse().getBanners());
            } else {
                isLastListEmpty = adapter.addBottomData(articleListEntity.getResponse().getFeeds().getList());
            }
            isHasMore = articleListEntity.getResponse().getFeeds().isHas_more();
            lastDataTime = articleListEntity.getResponse().getFeeds().getLast_time();
        } else {
            displayToast(articleListEntity.getMeta().getMsg());
        }
        qdRefreshListView.onRefreshComplete();
        onUIRefreshComplete();
    }

    @Override
    protected void onRequestErrorCallBack(NetUtil.NetParams params, Object response) {
        isLoading = false;
        qdRefreshListView.onRefreshComplete();
        qdRefreshListView.hasMoreLoadData(true, true);
    }

    @Override
    public void onResponseCache(NetUtil.NetParams params, JsonData response) {
        boolean isFirst = false;
        ArticleListEntity articleListEntity = null;

        if (params instanceof NetConfigs.RequestCategoriesArticles) {
            NetConfigs.RequestCategoriesArticles requestCategoriesArticles = (NetConfigs.RequestCategoriesArticles) params;
            isFirst = requestCategoriesArticles.getmLastTime() == 0;
        } else if (params instanceof NetConfigs.RequestHomesDada) {
            NetConfigs.RequestHomesDada requestHomesDada = (NetConfigs.RequestHomesDada) params;
            isFirst = requestHomesDada.getmLastTime() == 0;
        } else if (params instanceof NetConfigs.RequestTagsArticles) {
            NetConfigs.RequestTagsArticles requestTagsArticles = (NetConfigs.RequestTagsArticles) params;
            isFirst = requestTagsArticles.getmLastTime() == 0;
        } else if (params instanceof NetConfigs.RequestMyFavorite) {
            NetConfigs.RequestMyFavorite requestMyFavorite = (NetConfigs.RequestMyFavorite) params;
            isFirst = requestMyFavorite.getmLastTime() == 0;
        } else if (params instanceof NetConfigs.RequestRadarList) {
            NetConfigs.RequestRadarList requestRadarList = (NetConfigs.RequestRadarList) params;
            isFirst = requestRadarList.getmLastTime() == 0;
        } else if (params instanceof NetConfigs.RequestQuestionnaireLists) {
            NetConfigs.RequestQuestionnaireLists requestPaperList = (NetConfigs.RequestQuestionnaireLists) params;
            isFirst = requestPaperList.getmLastTime() == 0;
        }

        if (isFirst) {
            articleListEntity = QDJsonUtil.Json2Object(response.toString(), ArticleListEntity.class);
            if (null != articleListEntity && articleListEntity.getMeta().getStatus() == NetConfigs.HTTP_RESPONSE_200) {
                if (isFirst) //说明请求的第一页
                {
                    isLastListEmpty = adapter.addTopData(articleListEntity.getResponse().getFeeds().getList());
                    if (categoryDataObj.mCurCategoryFragmetType == QDEnum.CategoryFragmentEnum.HOME)
                        sliderBannerController.play(articleListEntity.getResponse().getBanners());
                }
            }
        }
    }

    @Override
    public void onRefreshBegin() {
        QLog.time(QDTAG + "onRefreshBegin");
        if (categoryDataObj.mCurCategoryFragmetType == QDEnum.CategoryFragmentEnum.SPIDERWEBCHART) {
            requestRadarList(0);
        } else {
            requestCategoriesArticles(0);
        }
    }

    private void requestRadarList(long lastTime) {
        if (isLoading)
            return;
        isLoading = true;
        getRequestManager().requestRadarList(categoryDataObj.categoryId, lastTime);
    }

    private void requestCategoriesArticles(long lastTime) {
        if (isLoading)
            return;
        isLoading = true;
        if (categoryDataObj.mCurCategoryFragmetType == QDEnum.CategoryFragmentEnum.CATEGORY || categoryDataObj.mCurCategoryFragmetType == QDEnum.CategoryFragmentEnum.BESTDESIGN) {
            getRequestManager().requestCategoriesArticles(categoryDataObj.categoryId, lastTime);
        } else if (categoryDataObj.mCurCategoryFragmetType == QDEnum.CategoryFragmentEnum.MYFAV) {
            getRequestManager().requestMyFavorite(lastTime);
        } else if (categoryDataObj.mCurCategoryFragmetType == QDEnum.CategoryFragmentEnum.HOME) {
            getRequestManager().requestHomes(lastTime);
        } else if (categoryDataObj.mCurCategoryFragmetType == QDEnum.CategoryFragmentEnum.TAG) {
            getRequestManager().requestTagsArticles(categoryDataObj.categoryId, lastTime);
        } else if (categoryDataObj.mCurCategoryFragmetType == QDEnum.CategoryFragmentEnum.PAPER) {
            getRequestManager().requestRequestQuestionnaireLists(lastTime);
        }
    }

    @Override
    public void onLoadMore() {
        if (isHasMore) {
            if (categoryDataObj.mCurCategoryFragmetType == QDEnum.CategoryFragmentEnum.SPIDERWEBCHART) {
                requestRadarList(lastDataTime);
            } else {
                requestCategoriesArticles(lastDataTime);
            }
        }
    }

    @Override
    public void onUIRefreshComplete() {
        qdRefreshListView.hasMoreLoadData(isLastListEmpty, isHasMore);
    }
}
